<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div>
      <div>
        <input type="file" @change="handleFileChange" name="file" id="file" />
      </div>
      <div v-if="isLoading">图片上传识别中....请稍后</div>
      <div>
        <button @click="getOcrData">上传并识别</button>
      </div>
      <div>
        识别内容：
        <p>
          {{ resultText }}
        </p>
      </div>
      <div>
        翻译后内容：
        <p>
          {{trans_resultText}}
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { getOcrData } from "@/api";

export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      file: null, //上传的文件变量
      resultText: "", //识别后显示的文本字符串
      isLoading: false,
      trans_resultText:"",
    };
  },
  methods: {
    handleFileChange(e) {
      //e等于element当前元素，获取选择后的文件
      this.file = e.target.files[0];
    },
    async getOcrData() {
      if (!this.file) {
        alert("请选择一张图片进行识别");
        return;
      }

      //设置识别状态
      this.isLoading = true;
      //新建一个formData表单对象
      const formData = new FormData();
      formData.append("file", this.file);
      let res = await getOcrData(formData);
      this.isLoading = false;
      if (res.state == 200) {
        this.resultText = res.data;
        this.resultText = this.resultText.replace(/\n/g, "");
        //识别成功后直接加载在线翻译方法
        this.translate_post();
      } else {
        alert("识别异常");
      }
    },
    //请求百度接口进行翻译
    async translate_post() {
      let appid = "20231025001859094";
      let salt = "1435660288";
      let key = "AhtvkPsafjoDu1YcGtOG";
      let sign = this.$md5(appid + this.resultText + salt + key);
      let params = {
        q: this.resultText,
        from: "auto",
        to: "zh",
        appid: appid,
        salt: salt,
        sign: sign,
      };
      //使用jsonp解决跨域问题
      this.$jsonp("https://fanyi-api.baidu.com/api/trans/vip/translate", params)
        .then((res) => {
          // console.log(res);
          this.trans_resultText = res.trans_result[0].dst;
        })
        .catch((error) => {
          console.log(error);
          this.trans_resultText = "翻译服务器异常";
        });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
